package com.lin.project.cloudnative.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lin.project.cloudnative.annotation.AuthCheck;
import com.lin.project.cloudnative.common.BaseResponse;
import com.lin.project.cloudnative.common.DeleteRequest;
import com.lin.project.cloudnative.common.ErrorCode;
import com.lin.project.cloudnative.common.ResultUtils;
import com.lin.project.cloudnative.constant.CommonConstant;
import com.lin.project.cloudnative.exception.BusinessException;
import com.lin.project.cloudnative.model.dto.testcase.TestCaseAddRequest;
import com.lin.project.cloudnative.model.dto.testcase.TestCaseQueryRequest;
import com.lin.project.cloudnative.model.dto.testcase.TestCaseUpdateRequest;
import com.lin.project.cloudnative.model.entity.TestCase;
import com.lin.project.cloudnative.model.entity.User;
import com.lin.project.cloudnative.service.TestCaseService;
import com.lin.project.cloudnative.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 测试用例接口
 */
@RestController
@RequestMapping("/testcase")
@Slf4j
public class TestCaseController {
    @Resource
    private TestCaseService testcaseService;

    @Resource
    private UserService userService;

    /**
     *
     *
     * @description: 添加测试用例
     * @param testcaseAddRequest
     * @param request
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 19:58
     */

    @PostMapping("/add")
    public BaseResponse<Long> addTestCase(@RequestBody TestCaseAddRequest testcaseAddRequest, HttpServletRequest request){
        if(testcaseAddRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TestCase testcase=new TestCase();
        BeanUtils.copyProperties(testcaseAddRequest,testcase);
        //校验
        testcaseService.validTestCase(testcase,true);
        User loginUser = userService.getLoginUser(request);
//        testcase.setUserId(loginUser.getId());
        boolean save = testcaseService.save(testcase);
        if(!save){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        Long id = testcase.getId();
        return ResultUtils.success(id);
    }

    /**
     *
     *
     * @description: 删除测试用例
     * @param deleteRequest
     * @param request
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:07
     */

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTestCase(@RequestBody DeleteRequest deleteRequest,HttpServletRequest request){
        if(deleteRequest==null || deleteRequest.getId()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long id = deleteRequest.getId();
        //判断是否存在
        TestCase testcase = testcaseService.getById(id);
        if(testcase==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //仅管理员和本人可以删除
//        if(!testcase.getUserId().equals(loginUser.getId()) && !userService.isAdmin(request)){
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//        }
        boolean b = testcaseService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     *
     *
     * @description: 测试用例更新
     * @param testcaseUpdateRequest
     * @param request
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:14
     */

    @PostMapping("/update")
    public BaseResponse<Boolean> updateTestCase(@RequestBody TestCaseUpdateRequest testcaseUpdateRequest,HttpServletRequest request){
        if(testcaseUpdateRequest==null || testcaseUpdateRequest.getId()<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TestCase testcase=new TestCase();
        BeanUtils.copyProperties(testcaseUpdateRequest,testcase);
        //参数校验
        testcaseService.validTestCase(testcase,false);
        User loginUser = userService.getLoginUser(request);
        Long id = testcaseUpdateRequest.getId();
        //判断是否存在
        TestCase oldTestCase = testcaseService.getById(id);
        if(oldTestCase==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //仅本人和管理员可以修改
//        if(!oldTestCase.getUserId().equals(loginUser.getId()) && !userService.isAdmin(request)){
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//        }
        boolean b = testcaseService.updateById(testcase);
        return ResultUtils.success(b);
    }

    /**
     *
     *
     * @description: 根据id获取测试用例信息
     * @param id
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:18
     */

    @GetMapping("/get")
    public BaseResponse<TestCase> getTestCaseById(Long id){
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TestCase testcase = testcaseService.getById(id);
        if(testcase.getIsdelete()==1){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"测试用例已删除");
        }
        return ResultUtils.success(testcase);
    }

    /**
     *
     *
     * @description: 获取测试用例列表，仅管理员可以使用
     * @param testcaseQueryRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:21
     */

    @GetMapping("/list")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<List<TestCase>> listTestCase(TestCaseQueryRequest testcaseQueryRequest){
        TestCase testcaseQuery=new TestCase();
        if(testcaseQueryRequest!=null){
            BeanUtils.copyProperties(testcaseQueryRequest,testcaseQuery);
        }
        QueryWrapper<TestCase> testcaseQueryWrapper = new QueryWrapper<>(testcaseQuery);
        List<TestCase> testcaseList = testcaseService.list(testcaseQueryWrapper);
        return ResultUtils.success(testcaseList);
    }

    /**
     *
     *
     * @description: 分页获取测试用例列表
     * @param testcaseQueryRequest
     * @return:
     * @author: linhuaixu
     * @time: 2023/5/17 20:33
     */

    @GetMapping("/list/page")
    public BaseResponse<Page<TestCase>> listTestCaseByPage(TestCaseQueryRequest testcaseQueryRequest){
        if(testcaseQueryRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TestCase testcase = new TestCase();
        BeanUtils.copyProperties(testcaseQueryRequest,testcase);
        long current = testcaseQueryRequest.getCurrent();
        long pageSize = testcaseQueryRequest.getPageSize();
        String sortField = testcaseQueryRequest.getSortField();
        String sortOrder = testcaseQueryRequest.getSortOrder();
//        String content = testcase.getContent();
//        //content需要支持模糊搜索
//        testcase.setContent(null);
        //限制爬虫
        if(pageSize>50){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<TestCase> testcaseQueryWrapper = new QueryWrapper<>(testcase);
//        testcaseQueryWrapper.like(StringUtils.isNotBlank(content),"content",content);
        testcaseQueryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField);
        Page<TestCase> page = testcaseService.page(new Page<>(current, pageSize), testcaseQueryWrapper);
        return ResultUtils.success(page);
    }

    @GetMapping("/list/ids")
    private BaseResponse<List<TestCase>> listTestCasesByIds(String ids){
        String[] split = ids.split(",");
        if(split==null || split.length<=0){
            return ResultUtils.success(new ArrayList<>());
        }
        List<TestCase> testCaseList = new ArrayList<>();
        for(String id:split){
            long l = Long.parseLong(id);
            BaseResponse<TestCase> testCaseById = this.getTestCaseById(l);
            testCaseList.add(testCaseById.getData());
        }
        return ResultUtils.success(testCaseList);
    }
}
